<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8" />
    <title>Jingwu 知识管理</title>
    <link rel="stylesheet" href="/kms/editormd/css/style.css" />
    <link rel="stylesheet" href="/kms/editormd/css/editormd.css" />
    <link rel="stylesheet" href="/kms/bootstrap/css/bootstrap.min.css" />
    <link rel="stylesheet" href="/kms/ztree/css/zTreeStyle/zTreeStyle.css" />
    <!-- <link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" /> -->
    <style>
        #header {position:relative; float:left; width:100%; text-align:left; }
        #header .h1{position:relative; float:left; width:20%; text-align:left; }
        #action {position:relative; float:right; width:20%; text-align:right; display: none; }
        #ztree {position:relative; float:left; width:10%; text-align:left; }
        #editor {width: 85%; margin: 0 auto; display:none; }
        #preview {width: 85%; margin: 0 auto; display:none; }
    </style>
</head>
<body>
<div id="header">
    <div class="h1">
        <h1>知识管理系统<h1>
    </div>
    <div id="action" class="btn-group" role="group">
        <button id="action_edit"    type="button" class="btn btn-default" style="display:none;" onclick="edit_view();">编辑</button>
        <button id="action_save"    type="button" class="btn btn-default" style="display:none;" onclick="edit_save();">保存</button>
        <button id="action_cancel"  type="button" class="btn btn-default" style="display:none;" onclick="edit_cancel();">取消</button>
        <button id="action_login"   type="button" class="btn btn-default" style="display:none;" data-toggle="modal" data-target="#loginModal">登录</button>
        <button id="action_logout"  type="button" class="btn btn-default" style="display:none;" onclick="user_logout();">退出</button>
    </div>
</div>
<div id="ztree" class="ztree"></div>
<div id="editor"></div>
<div id="preview"></div>

<div class="modal fade" id="loginModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">登录</h4>
      </div>
      <div class="modal-body">
        <form class="form-inline">
          <div class="form-group">
            <label for="recipient-name" class="control-label">用户名</label>
            <input type="text" class="form-control" id="username">
          <br/>
            <label for="message-text" class="control-label">密&nbsp;&nbsp;&nbsp;码</label>
            <input type="text" class="form-control" id="password">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" onclick="user_login();">登录</button>
      </div>
    </div>
  </div>
</div>

<script src="/kms/editormd/js/jquery.min.js"></script>
<script src="/kms/editormd/js/marked.min.js"></script>
<script src="/kms/editormd/js/prettify.min.js"></script>
<script src="/kms/editormd/js/raphael.min.js"></script>
<script src="/kms/editormd/js/underscore.min.js"></script>
<script src="/kms/editormd/js/sequence-diagram.min.js"></script>
<script src="/kms/editormd/js/flowchart.min.js"></script>
<script src="/kms/editormd/js/jquery.flowchart.min.js"></script>
<script src="/kms/editormd/js/editormd.js"></script>
<script src="/kms/bootstrap/js/bootstrap.min.js"></script>
<script src="/kms/ztree/js/jquery.ztree.core.min.js"></script>
<script type="text/javascript">
var editor;
var loginKey = 'doc_login';
var urlKey = 'doc_url';
//设置cookie
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
}
//获取cookie
function getCookie(name) {
    var result,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    result =document.cookie.match(reg);
    return result ? unescape(result[2]) : null;
}
//清除cookie
function delCookie(name) {
    setCookie(name, "", -1);
}

function edit_view() {
    $('#action_edit').hide();
    $('#action_save').show();
    $('#action_cancel').show();
    showEditor(getEditorPkey(), false);
}

function edit_cancel() {
    $('#action_edit').show();
    $('#action_cancel').hide();
    showEditor(getEditorPkey());
}

function edit_save() {
    $('#action_edit').show();
    $('#action_cancel').hide();
    $('#action_save').hide();
    content = editor.getMarkdown();
    pkey = getCookie(urlKey);
    $.ajax({
        url: '/save',
        data: 'pkey=' + pkey + '&markdown='+encodeURI(content),
        method: 'post',
        success: function(message) {
            if(message.substr(0,2) != "ok") alert("保存失败");
        },
    });
    setTimeout("showEditor(getEditorPkey());", 1000);
}

function createEditor(markdown, isEditor = false) {
    var setting = {
        width           : "90%",
        //height          : 580,
        path            : './kms/editormd/js/',
        markdown        : markdown ,
        //htmlDecode      : true,
        htmlDecode      : "style,script,iframe",
        //toc             : false,
        tocm            : true, 
        //tocContainer    : "#custom-toc-container",
        //gfm             : false,
        //tocDropdown     : true,
        // markdownSourceCode : true,
        emoji           : true,
        taskList        : true,
        tex             : true,  // 默认不解析
        flowChart       : true,  // 默认不解析
        sequenceDiagram : true  // 默认不解析
    };
    //editor = isEditor ? editormd("preview", setting) : editormd.markdownToHTML("preview", setting);
    if(isEditor) {
        editor = editormd("editor", setting);
    } else {
        editormd.markdownToHTML("preview", setting);
    }
}

function nodeClick(event, treeId, treeNode, clickFlag) {
    if(treeNode['isParent']) return true;
    setEditorPkey(treeNode['pkey']);
    showEditor(getEditorPkey());
}

function ajaxTreeFilter(treeId, parentNode, content) {
    prefix = parentNode == undefined ? '' : parentNode['pkey'];
    lines = content.split("\n");
    var nodes = [];
    var nodesFile = [];
    var filter = ['index.html', '404.html', 'LICENSE', 'kms/'];
    for(var i in lines) {
        if(filter.toString().indexOf(lines[i]) > -1) continue;
        var pkey = prefix + lines[i];
        if(lines[i].substr(-1) == '/') {
            nodes.push({'name':lines[i], 'pkey':pkey, 'isParent':true});
        } else {
            nodesFile.push({'name':lines[i], 'pkey':pkey});
        }
    }
    for(var i in nodesFile) {
        nodes.push(nodesFile[i]);
    }
    return nodes;
}

function showEditor(pkey, isPreview = true) {
    var content = '';
    $.ajax({
        url:pkey,
        async:false,
        success: function(raw) {
            content = raw;
        }
    });
    $('#editor').html('');
    $('#preview').html('');
    if(isPreview) {
        $('#editor').hide();
        $('#preview').show();
        createEditor(content, false)
    } else {
        $('#editor').show();
        $('#preview').hide();
        createEditor(content, true)
    }
}

function setEditorPkey(pkey) {
    setCookie(urlKey, pkey);
}

function getEditorPkey() {
    return getCookie(urlKey);
}

function user_login() {
    var username = $('#username').val();
    var password = $('#password').val();
    $.ajax({
        url: '/login',
        data: 'username=' + username + '&password=' + password,
        method: 'post',
        success: function(message) {
            message = $.trim(message);
            if(message == "ok") {
                setCookie(loginKey, 1);
                $('#loginModal').modal('hide');
                show();
            } else {
                alert("登录失败！");
            }
        },
    });
}

function user_logout() {
    delCookie('doc_login');
    location.reload()
    //show();
}

function show() {
    $('#action').show();
    if(getCookie('doc_login')) {
        $('#action_edit').show();
        $('#action_login').hide();
        $('#action_logout').show();
    } else {
        $('#action_login').show();
        $('#action_logout').hide();
    }
}

var setting = {
    async: {
        enable: true,
        url:"/dir",
        type:"get",
        autoParam:["id", "pkey"],
        dataFilter: ajaxTreeFilter
    },
    callback: {
        onClick: nodeClick
    }
};

$(document).ready(function() {
    $.fn.zTree.init($("#ztree"), setting);
    result = getEditorPkey();
    if(!result) setEditorPkey('readme.md');
    showEditor(getEditorPkey(), true);
    show();
});
</script>
</body>
</html>
